package com.hnucm.c201901020241.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.hnucm.c201901020241.R;

import com.hnucm.c201901020241.my.AboutUsActivity;
import com.hnucm.c201901020241.my.Public;
import com.hnucm.c201901020241.my.Shoucang;
import com.hnucm.c201901020241.my.UpdatePersonalInformation;
import com.hnucm.c201901020241.utils.BlurTransformation;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

import static android.content.Context.MODE_MULTI_PROCESS;
import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

public class MyFragment extends Fragment {
    TextView usernameTv,signatureTv;
    ImageView hBack,hHead;
    String touxiang,name,signature,account;
    Uri uri;//头像
    String imageString;
    Boolean isselect=false;
    private String TAG = MyFragment.class.getSimpleName();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
//可见时执行的操作
//            点击了当前的页面
            isselect=true;
            Log.i("main1","是我");
        }else{
            isselect=false;
            Log.i("main1","不是我");
//不可见时执行的操作
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init_view();//初始化各组件
        init_action();//初始化监听事件
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("init1",false);
        editor.putBoolean("init2",false);
        editor.putBoolean("init3",true);
        editor.putBoolean("init4",true);
        editor.commit();

        Boolean init=sharedPreferences.getBoolean("init4",false);
        Boolean isfirst=sharedPreferences.getBoolean("isfirst4",false);
        if(init&&!isfirst&&isselect){
            init_NewbieGuide();
            editor.putBoolean("isfirst4",true);
            editor.commit();
        }

    }

    private void init_NewbieGuide() {
        Log.i("main1","4也进来了");
        Animation enterAnimation = new AlphaAnimation(0f, 1f);
        enterAnimation.setDuration(600);
        enterAnimation.setFillAfter(true);

        Animation exitAnimation = new AlphaAnimation(1f, 0f);
        exitAnimation.setDuration(600);
        exitAnimation.setFillAfter(true);

        NewbieGuide.with(this)
                .setLabel("MyFragment")//设置引导层标示区分不同引导层，必传！否则报错
                .setShowCounts(1)
                .setOnGuideChangedListener(new OnGuideChangedListener() {//引导层显示监听
                    @Override
                    public void onShowed(Controller controller) {
                        Log.e(TAG, "NewbieGuide onShowed: ");
                        //引导层显示
                    }

                    @Override
                    public void onRemoved(Controller controller) {//引导层隐藏监听
                        Log.e(TAG, "NewbieGuide  onRemoved: ");
                        //引导层消失（多页切换不会触发）
                    }
                })
                .setOnPageChangedListener(new OnPageChangedListener() {//引导页切换监听
                    @Override
                    public void onPageChanged(int page) {
                        Log.e(TAG, "NewbieGuide  onPageChanged: " + page);
                        //引导页切换，page为当前页位置，从0开始
                    }
                })
                .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                /**
                 * 添加引导页一
                 */
                .addGuidePage(//添加一页引导页
                        GuidePage.newInstance()//创建一个实例
                                .addHighLight(getActivity().findViewById(R.id.shoucang))//添加高亮的view
                                .addHighLight(getActivity().findViewById(R.id.shoucang), HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.myfragment_style1)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )
                .addGuidePage(
                        GuidePage.newInstance()
                            .addHighLight(getActivity().findViewById(R.id.update))
                            .addHighLight(getActivity().findViewById(R.id.update), HighLight.Shape.RECTANGLE)
                            .setLayoutRes(R.layout.myfragment_style2)//设置引导页布局
                            .setEnterAnimation(enterAnimation)//进入动画
                            .setExitAnimation(exitAnimation)//退出动画*/
                )
                .addGuidePage(
                        GuidePage.newInstance()
                            .addHighLight(getActivity().findViewById(R.id.mysubmission))
                            .addHighLight(getActivity().findViewById(R.id.mysubmission), HighLight.Shape.RECTANGLE)
                            .setLayoutRes(R.layout.myfragment_style3)//设置引导页布局
                            .setEnterAnimation(enterAnimation)//进入动画
                            .setExitAnimation(exitAnimation)//退出动画*/
                )
                .addGuidePage(
                        GuidePage.newInstance()
                                .addHighLight(getActivity().findViewById(R.id.aboutus))
                                .addHighLight(getActivity().findViewById(R.id.aboutus), HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.myfragment_style4)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )
                /**
                 * 展示
                 */
                .show();//显示引导层(至少需要一页引导页才能显示)
    }

    private void init_action() {
        getActivity().findViewById(R.id.shoucang).setOnClickListener(new View.OnClickListener() {//点击收藏夹的监听
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), Shoucang.class);
                startActivity(intent);
            }
        });
        getActivity().findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {//点击更新信息的监听
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), UpdatePersonalInformation.class);
                startActivity(intent);
            }
        });
        getActivity().findViewById(R.id.mysubmission).setOnClickListener(new View.OnClickListener() {//点击我的发布的监听
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), Public.class);
                startActivity(intent);
            }
        });
        getActivity().findViewById(R.id.aboutus).setOnClickListener(new View.OnClickListener() {//点击关于我们的监听
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), AboutUsActivity.class);
                startActivity(intent);
            }
        });

       hHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                弹窗选择图片
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                galleryIntent.setType("image/*");//图片
                startActivityForResult(galleryIntent, 0);
            }
        });

    }

    private void show_image(){
        x.Ext.init(getActivity().getApplication());
        RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryimage?");
        requestParams.addQueryStringParameter("account",account);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
                byte[] imageBytes = Base64.decode(result, Base64.DEFAULT);
                Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                hHead.setImageBitmap(decodedImage);
                SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",MODE_MULTI_PROCESS);//MODE_PRIVATE私有权限，保护文件
                SharedPreferences.Editor editor=sharedPreferences.edit();
                editor.putString("base64", result);
                editor.commit();
                Glide.with(getActivity()).load(decodedImage)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(hHead);
                Glide.with(getActivity()).load(decodedImage)
                        .transform(new BlurTransformation(getActivity(),25),new CenterCrop())
                        .into(hBack);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void init_view(){
        hBack=getActivity().findViewById(R.id.h_back);
        hHead=getActivity().findViewById(R.id.h_head);
        usernameTv=getActivity().findViewById(R.id.user_name);
        signatureTv=getActivity().findViewById(R.id.user_val);
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        touxiang= sharedPreferences.getString("base64", "null");
        name= sharedPreferences.getString("name","");
        account=sharedPreferences.getString("account","");
        signature=sharedPreferences.getString("signature","");
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("isfirst2",false);
        //设置背景磨砂效果
        byte[] imageBytes = Base64.decode(touxiang, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        Glide.with(getActivity()).load(decodedImage)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(hHead);
        Glide.with(this).load(decodedImage)
                .transform(new BlurTransformation(getActivity(),25),new CenterCrop())
                .into(hBack);
//        //设置圆形图像
//        Glide.with(this).load(touxiang).into(hHead);
        usernameTv.setText(name);
        signatureTv.setText(signature);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // TODO Auto-generated method stub
        if (requestCode == 0 && resultCode == -1) {
            uri = data.getData();
            Log.i("tt", uri.getPath());
            Log.i("tt", uri.getEncodedPath());

            //将图片转换成Base64编码
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//                System.out.println(imageString);
                x.Ext.init(getActivity().getApplication());
                RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/updateimage?");
                requestParams.addQueryStringParameter("account", account);
                requestParams.addBodyParameter("image",imageString);
                x.http().post(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        show_image();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } catch (Exception e) {

            }


        }
    }

}